/* On{X} Script: Change volume to 50% when I reach work and back to 100% on leaving
 *
 * Developer: Gaurav Nandwani
 *
 * Description:
 *
 * This rule monitors phone's location using defined region by latitude & longitude. It changes
 * ringer volume on entering the loacation and changes it back on leaving the region.
 * 
 * Usage:
 * 
 * Change the values "location" variable:
 *      name        - Name of the location.
 *      latitude    - Latitude of the location. 
 *      longitude   - Longitude of the location.
 * volume_enter     - Ringer volume for when you enter the region
 * volume_leave     - Ringer volume for when you leave the region
 *
 * You can use Google Maps or Bing Maps to determine the latitude & 
 * longitude of your home.
 */
  
// Initializing variables
 
var location = { name : 'work', latitude : '12.82787', longitude : '80.21936' };
var volume_enter = 50; /* 0 - 100 */
var volume_leave = 100; /* 0 - 100 */

// End of variables initializing 

console.log('Started script: Turn ringer volume to ' + volume_enter + ' while I am at '+ location.name + ' and back to ' + volume_leave + ' when I leave.');

// create a geo region for the trigger to take place at
var region = device.regions.createRegion({
    latitude: parseFloat(location.latitude, 10),
    longitude: parseFloat(location.longitude, 10),
    name: location.name,
    radius: 500
});

// register a callback to set volume for stream on entering/exiting the region
region.on('enter', function () {
    // change the volume and initiate a notification with the reminder
    device.audio.ringerVolume = volume_enter;
    device.media.volume = volume_enter;
    device.notifications.createNotification('Changed volume to ' + volume_enter + '% as you entered ' + location.name).show();
});

region.on('exit', function() {
    // change the volume and initiate a notification with the reminder
	device.audio.ringerVolume = volume_leave;
    device.media.volume = volume_leave;
	device.notifications.createNotification('Changed volume to ' + volume_leave + '% as you left ' + location.name).show();
});

// start monitoring the region
device.regions.startMonitoring(region);
console.log('Completed script: Turn ringer volume to ' + volume_enter + ' while I am at '+ location.name + ' and back to ' + volume_leave + ' when I leave.');
